package com.tjetc.controller;


import com.tjetc.anno.MyLog;
import com.tjetc.domain.dto.OrderDTO;
import com.tjetc.domain.po.Orders;
import com.tjetc.domain.vo.OrderVo;
import com.tjetc.service.IOrdersService;
import com.tjetc.utils.PageBean;
import com.tjetc.utils.PoToVoUtil;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private PoToVoUtil poToVoUtil;

    @GetMapping("/xxx")
    public String xxx() {
        return "hello";
    }


    @MyLog
    @PostMapping("/sale")
    public Long sale(@RequestBody OrderDTO orderDTO) {
        return ordersService.sale(orderDTO);

    }


    @Scheduled(fixedRate = 1000 * 60 * 30)
    public void cancelOrders() {
        // 查询所有未支付且超过30分钟的订单
        List<Orders> orders = ordersService.findUnpaidOrdersOver30Minutes();
        for (Orders order : orders) {
            OrderVo orderVo = poToVoUtil.toOrderVo(order);
            ordersService.cancelOrder(orderVo);
        }
    }


    @MyLog
    @GetMapping("/cancel")
    public String cancelOrdersById(Integer id) {
        Orders order = ordersService.findById(id);
        return ordersService.cancelOrder(poToVoUtil.toOrderVo(order));
    }


    @GetMapping("/list")
    public PageBean<OrderVo> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "2") Integer pageSize,
            String status,
            String startTime,
            String endTime,
            Integer userId
    ) {
        return ordersService.list(pageNum, pageSize, status, startTime, endTime, userId);
    }


    @Scheduled(fixedRate = 1000 )
    public void finish() {
        //查询所有 演出时间+2小时 大于当前时间 且状态为已支付的订单
        List<Orders> orders = ordersService.findPaidOrdersOverStart();
        // 遍历订单列表，完成订单
        for (Orders order : orders) {
            ordersService.finishOrder(order);
        }
    }


}
